<!-- 出货检验单表单组件 -->
<template>
  <div class="oqc-form">
    <!-- 导航标签 -->
    <el-tabs v-model="activeTab" type="card" class="form-tabs">
      <el-tab-pane label="基本信息" name="basicInfo"></el-tab-pane>
      <el-tab-pane :label="form.oqcId ? '产品完整信息' : '客户信息'" name="productInfo"></el-tab-pane>
      <el-tab-pane label="检测信息" name="testData" v-if="form.oqcId"></el-tab-pane>
      <el-tab-pane label="检测结果" name="testResult" v-if="form.oqcId"></el-tab-pane>
      <el-tab-pane label="检测项" name="testItems" v-if="form.oqcId"></el-tab-pane>
    </el-tabs>

    <!-- 表单内容区域 -->
    <div class="form-content-area">
      <!-- 基本信息卡片 -->
      <el-card class="form-card" shadow="hover" v-show="activeTab === 'basicInfo'">
        <div slot="header" class="card-header">
          <span>基本信息与来源</span>
        </div>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="form-container">
          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="出货检验单编号" prop="oqcCode" class="form-item" required>
                <div class="input-with-btn">
                  <el-input
                    v-model="form.oqcCode"
                    placeholder="请输入出货检验单编号"
                    :disabled="form.oqcId || type === 'edit'"
                    :class="{'disabled-input': form.oqcId || type === 'edit'}"
                    @input="handleInputChange('oqcCode')">
                    <el-button
                      v-if="!form.oqcId && type !== 'edit'"
                      slot="append"
                      type="primary"
                      icon="el-icon-refresh"
                      class="inner-button"
                      @click="handleGenerateCode"
                      :loading="codeLoading">
                      生成
                    </el-button>
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="出货检验单名称" prop="oqcName" class="form-item" required>
                <el-input v-model="form.oqcName" placeholder="请输入出货检验单名称" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="10" v-if="form.oqcId">
              <el-form-item label="检验模板ID" prop="templateId" class="form-item" required>
                <div class="input-with-btn">
                  <el-input
                    v-model="form.templateId"
                    placeholder="请输入检验模板ID"
                    @input="handleInputChange('templateId')">
                    <el-button
                      slot="append"
                      type="primary"
                      icon="el-icon-search"
                      class="inner-button"
                      @click="openTemplatePlanSelector">
                      选择
                    </el-button>
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
            
          </el-row>

          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="单据状态" prop="status" class="form-item" required>
                <el-select v-model="form.status" placeholder="请选择单据状态" style="width: 100%" disabled>
                  <el-option label="草稿" value="1" />
                  <el-option label="已提交" value="2" />
                  <el-option label="已审核" value="3" />
                </el-select>
                <div class="form-tip" v-if="form.status">
                  <i class="el-icon-info"></i> 单据状态: {{ form.status === '1' ? '草稿' : form.status === '2' ? '已提交' : '已审核' }}（系统自动设置）
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="来源单据类型" prop="sourceDocType" class="form-item" required>
                <el-select v-model="form.sourceDocType" placeholder="请选择来源单据类型" style="width: 100%">
                  <el-option label="出货单" value="1" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="来源单据编号" prop="sourceDocCode" class="form-item" required>
                <div class="input-with-btn">
                  <el-input
                    v-model="form.sourceDocCode"
                    placeholder="请输入来源单据编号"
                    @input="handleInputChange('sourceDocCode')">
                    <el-button
                      slot="append"
                      type="primary"
                      icon="el-icon-search"
                      class="inner-button"
                      @click="openSalesSelector">
                      选择
                    </el-button>
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="来源单据ID" prop="sourceDocId" class="form-item" required>
                <el-input v-model="form.sourceDocId" placeholder="请输入来源单据ID" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 产品信息卡片 -->
      <el-card class="form-card" shadow="hover" v-show="activeTab === 'productInfo'">
        <div slot="header" class="card-header">
          <span>{{ form.oqcId ? '产品完整信息' : '客户信息' }}</span>
        </div>
        <el-form :model="form" label-width="120px" class="form-container">
          <!-- 客户信息区域 -->
          <div class="section-header">客户信息</div>
          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="客户ID" prop="customerId" class="form-item" required>
                <el-input v-model="form.customerId" placeholder="请输入客户ID" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="客户编码" prop="customerCode" class="form-item" required>
                <el-input v-model="form.customerCode" placeholder="请输入客户编码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="客户名称" prop="customerName" class="form-item" required>
                <el-input v-model="form.customerName" placeholder="请输入客户名称" />
              </el-form-item>
            </el-col>
            
          </el-row>

          <!-- 产品详细信息区域 - 只在编辑模式显示 -->
          <template v-if="form.oqcId">
            <div class="section-header">产品详细信息</div>
            <el-row :gutter="30">
              <el-col :span="10">
                <el-form-item label="产品ID" prop="productId" class="form-item" required>
                  <el-input v-model="form.productId" placeholder="请输入产品ID" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="产品编码" prop="productCode" class="form-item" required>
                  <el-input v-model="form.productCode" placeholder="请输入产品编码" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="10">
                <el-form-item label="产品名称" prop="productName" class="form-item" required>
                  <el-input v-model="form.productName" placeholder="请输入产品名称" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="产品规格型号" prop="productSfn" class="form-item" required>
                  <el-input v-model="form.productSfn" placeholder="请输入产品规格型号" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="30">
              <el-col :span="10">
                <el-form-item label="单位" prop="unit" class="form-item" required>
                  <el-input v-model="form.unit" placeholder="请输入单位" readonly />
                </el-form-item>
              </el-col>
            </el-row>
          </template>
        </el-form>
      </el-card>

      <!-- 检测基本信息卡片 -->
      <el-card class="form-card" shadow="hover" v-show="activeTab === 'testData'">
        <div slot="header" class="card-header">
          <span>检测基本信息</span>
        </div>
        <el-form :model="form" label-width="120px" class="form-container">
          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="最低检测数" prop="quantityMinCheckNum" class="form-item">
                <el-input-number v-model="form.quantityMinCheckNum" placeholder="请输入最低检测数" :min="0" :precision="0" style="width: 100%" :disabled="true" />
                <div class="form-tip" v-if="form.quantityMinCheckNum">
                  <i class="el-icon-info"></i> 规定最低检测数: {{ form.quantityMinCheckNum }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="最大不合格数" prop="quantityMaxUnqualifiedNum" class="form-item">
                <el-input-number v-model="form.quantityMaxUnqualifiedNum" placeholder="请输入最大不合格数" :min="0" :precision="0" style="width: 100%" :disabled="true" />
                <div class="form-tip" v-if="form.quantityMaxUnqualifiedNum">
                  <i class="el-icon-info"></i> 规定最大不合格数: {{ form.quantityMaxUnqualifiedNum }}，超过此值将自动判定为不合格
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="发货数量" prop="quantityOutNum" class="form-item" required>
                <el-input-number v-model="form.quantityOutNum" placeholder="请输入发货数量" :min="0" :precision="0" style="width: 100%" @change="handleOutNumChange" :disabled="type === 'edit'" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="本次检测数量" prop="quantityCheckNum" class="form-item" required>
                <el-input-number v-model="form.quantityCheckNum" placeholder="请输入本次检测数量" :min="0" :precision="0" style="width: 100%" @change="handleQuantityChange" />
                <div class="form-tip warning" v-if="form.quantityMinCheckNum && form.quantityCheckNum < form.quantityMinCheckNum">
                  <i class="el-icon-warning"></i> 检测数量低于规定最低检测数
                </div>
                <div class="form-tip warning" v-if="form.quantityOutNum && form.quantityCheckNum > form.quantityOutNum">
                  <i class="el-icon-warning"></i> 检测数量不能超过发货数量
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="不合格数" prop="quantityUnqualifiedNum" class="form-item" required>
                <el-input-number 
                  v-model="form.quantityUnqualifiedNum" 
                  placeholder="请输入不合格数" 
                  :min="0" 
                  :max="form.quantityCheckNum || 0" 
                  :precision="0" 
                  style="width: 100%" 
                  @change="handleUnqualifiedNumChange" 
                />
                <div class="form-tip warning" v-if="form.quantityMaxUnqualifiedNum && form.quantityUnqualifiedNum > form.quantityMaxUnqualifiedNum">
                  <i class="el-icon-error" style="color: #F56C6C;"></i> <strong>不合格数已超过规定最大值({{form.quantityMaxUnqualifiedNum}})，检测结果已自动设为不合格</strong>
                </div>
                <div class="form-tip" v-else-if="form.quantityMaxUnqualifiedNum">
                  <i class="el-icon-info"></i> 最大允许不合格数: {{ form.quantityMaxUnqualifiedNum }}，超过此值将自动判定为不合格
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="合格数量" prop="quantityQuanlifiedNum" class="form-item" required>
                <el-input-number 
                  v-model="form.quantityQuanlifiedNum" 
                  placeholder="请输入合格数量" 
                  :min="0" 
                  :max="form.quantityCheckNum || 0" 
                  :precision="0" 
                  style="width: 100%" 
                  @change="handleQualifiedNumChange" 
                />
                <div class="form-tip" v-if="form.quantityCheckNum">
                  <i class="el-icon-info"></i> 检测数量: {{ form.quantityCheckNum }}，修改一项数量会自动调整另一项
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="检测结果" prop="checkResult" class="form-item" required>
                <el-select v-model="form.checkResult" placeholder="请选择检测结果" style="width: 100%">
                  <el-option label="合格" value="1" />
                  <el-option label="不合格" value="2" />
                  <el-option label="待检" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="出货日期" prop="outDate" class="form-item" required>
                <el-date-picker
                  v-model="form.outDate"
                  type="date"
                  placeholder="请选择出货日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="检测日期" prop="inspectDate" class="form-item" required>
                <el-date-picker
                  v-model="form.inspectDate"
                  type="date"
                  placeholder="请选择检测日期"
                  value-format="yyyy-MM-dd"
                  style="width: 100%"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="检测人员" prop="inspectorId" class="form-item" required>
                <el-input
                  v-model="form.inspectorName"
                  placeholder="请选择检测人员"
                  readonly
                  style="width: 80%; display: inline-block;"
                  @focus="openUserDialog"
                />
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="openUserDialog"
                  style="margin-left: 8px;"
                >选择</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 检测结果详情卡片 - 只在编辑模式下显示 -->
      <el-card class="form-card" shadow="hover" v-show="activeTab === 'testResult' && form.oqcId">
        <div slot="header" class="card-header">
          <span>检测结果详情</span>
        </div>
        <el-form :model="form" label-width="120px" class="form-container">
          <div class="section-header">缺陷率信息</div>
          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="致命缺陷率" prop="crRate" class="form-item" required>
                <el-input v-model="form.crRate" placeholder="请输入致命缺陷率" :disabled="true" />
                <div class="form-tip" v-if="form.crRate">
                  <i class="el-icon-info"></i> 致命缺陷率：{{ form.crRate }}%
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="严重缺陷率" prop="majRate" class="form-item" required>
                <el-input v-model="form.majRate" placeholder="请输入严重缺陷率" :disabled="true" />
                <div class="form-tip" v-if="form.majRate">
                  <i class="el-icon-info"></i> 严重缺陷率：{{ form.majRate }}%
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="轻微缺陷率" prop="minRate" class="form-item" required>
                <el-input v-model="form.minRate" placeholder="请输入轻微缺陷率" :disabled="true" />
                <div class="form-tip" v-if="form.minRate">
                  <i class="el-icon-info"></i> 轻微缺陷率：{{ form.minRate }}%
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="section-header">缺陷数量信息</div>
          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="致命缺陷数量" prop="crQuantityNum" class="form-item" required>
                <el-input-number
                  v-model="form.crQuantityNum"
                  placeholder="请输入致命缺陷数量"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="calculateDefectRates"
                  :disabled="!form.quantityUnqualifiedNum || form.quantityUnqualifiedNum <= 0"
                  :max="(form.quantityUnqualifiedNum || 0) - (form.majQuantityNum || 0) - (form.minQuantityNum || 0)"
                />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="严重缺陷数量" prop="majQuantityNum" class="form-item" required>
                <el-input-number
                  v-model="form.majQuantityNum"
                  placeholder="请输入严重缺陷数量"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="calculateDefectRates"
                  :disabled="!form.quantityUnqualifiedNum || form.quantityUnqualifiedNum <= 0"
                  :max="(form.quantityUnqualifiedNum || 0) - (form.crQuantityNum || 0) - (form.minQuantityNum || 0)"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <el-col :span="10">
              <el-form-item label="轻微缺陷数量" prop="minQuantityNum" class="form-item" required>
                <el-input-number
                  v-model="form.minQuantityNum"
                  placeholder="请输入轻微缺陷数量"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  @change="calculateDefectRates"
                  :disabled="!form.quantityUnqualifiedNum || form.quantityUnqualifiedNum <= 0"
                  :max="(form.quantityUnqualifiedNum || 0) - (form.crQuantityNum || 0) - (form.majQuantityNum || 0)"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <div class="section-header">备注信息</div>
          <el-row :gutter="30">
            <el-col :span="20">
              <el-form-item label="备注" prop="remark" class="form-item">
                <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" :rows="4" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 检测项列表 -->
      <div v-show="activeTab === 'testItems' && form.oqcId" class="test-items-container">
        <oqc-line-table
          ref="oqcLineTable"
          :oqcId="form.oqcId"
          :editable="form.status !== '3'"
        />
      </div>
    </div>

    <!-- 底部按钮区域 -->
    <div class="form-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 检验模板选择器 -->
    <template-plan-selector
      :visible.sync="templateSelectorVisible"
      @select="handleTemplateSelect"
      @close="templateSelectorVisible = false"
    />

    <!-- 员工选择弹窗 -->
    <select-user-dialog
      :visible.sync="userDialogVisible"
      title="选择检测人员"
      :multi="false"
      @confirm="handleUserConfirm"
    />

    <!-- 出货单选择对话框 -->
    <el-dialog
      title="选择出货单"
      :visible.sync="salesDialogVisible"
      width="70%"
      append-to-body
    >
      <div class="dialog-content">
        <el-form :inline="true" :model="salesQueryParams" class="search-form">
          <el-form-item label="出货单编码">
            <el-input
              v-model="salesQueryParams.sales_code"
              placeholder="请输入出货单编码"
              clearable
              @keyup.enter.native="handleSalesQuery"
            />
          </el-form-item>
          <el-form-item label="出货单名称">
            <el-input
              v-model="salesQueryParams.sales_name"
              placeholder="请输入出货单名称"
              clearable
              @keyup.enter.native="handleSalesQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSalesQuery">搜索</el-button>
          </el-form-item>
        </el-form>

        <el-table
          v-loading="salesLoading"
          :data="salesList"
          height="400"
          @row-click="handleSalesSelect"
        >
          <el-table-column prop="sales_code" label="出货单编码" width="180" />
          <el-table-column prop="sales_name" label="出货单名称" width="180" />
          <el-table-column prop="customer_id" label="客户ID" width="120" />
          <el-table-column prop="customer_code" label="客户编码" width="120" />
          <el-table-column prop="customer_name" label="客户名称" width="180" />
          <el-table-column prop="sales_date" label="出货日期" width="180">
            <template slot-scope="scope">
              {{ formatDate(scope.row.sales_date) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click.stop="handleSalesSelect(scope.row)"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOqc, addOqc, updateOqc, selectCkProductSales } from "@/api/qc/OutgoingInspection"
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers.js"
import { getQcTemplateProductList } from "@/api/qc/IncomingInspection"
import { selectQcTemplateProductMaterialCode, selectQcTemplateProductProductCode } from "@/api/qc/QualitySchemeOrder"
import TemplatePlanSelector from "./TemplatePlanSelector.vue"
import OqcLineTable from "./OqcLineTable.vue"
import SelectUserDialog from '@/views/qc/components/SelectUserDialog.vue'

export default {
  name: "OqcForm",
  components: {
    TemplatePlanSelector,
    OqcLineTable,
    SelectUserDialog
  },
  props: {
    // 是否显示
    visible: {
      type: Boolean,
      default: false
    },
    // 标题
    title: {
      type: String,
      default: ""
    },
    // 编辑时的ID，没有则是新增
    oqcId: {
      type: [Number, String],
      default: null
    }
  },
  computed: {
    // 计算属性：根据oqcId判断当前是编辑模式还是新增模式
    type() {
      return this.oqcId || this.form.oqcId ? 'edit' : 'add';
    }
  },
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'basicInfo',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      // 是否显示弹出层
      open: false,
      // 编码生成加载状态
      codeLoading: false,
      // 是否使用系统编号
      isSystemCode: true,
      // 检验模板选择器显示状态
      templateSelectorVisible: false,
      // 员工选择弹窗显示状态
      userDialogVisible: false,
      // 出货单选择对话框显示状态
      salesDialogVisible: false,
      // 出货单加载状态
      salesLoading: false,
      // 出货单列表
      salesList: [],
      // 出货单查询参数
      salesQueryParams: {
        sales_code: '',
        sales_name: ''
      },
      // 检测方案参数，用于验证和自动判断结果
      templateParams: {
        quantityCheckNum: 0,          // 最低检测数
        quantityUnqualifiedNum: 0,    // 最大不合格数
        crRate: 0,                   // 致命缺陷率
        majRate: 0,                  // 严重缺陷率
        minRate: 0                   // 轻微缺陷率
      },
      // 表单参数
      form: {
        oqcId: null,
        oqcCode: null,
        oqcName: null,
        templateId: null,
        templateCode: null,
        templateName: null,
        sourceDocId: null,
        sourceDocType: '1', // 默认为出货单
        sourceDocCode: null,
        sourceLineId: null,
        customerId: null,
        customerCode: null,
        customerName: null,
        batchCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSfn: null,
        unit: null,
        quantityMinCheckNum: 0,
        quantityMaxUnqualifiedNum: 0,
        quantityOutNum: 0,
        quantityCheckNum: 0,
        quantityUnqualifiedNum: 0,
        quantityQuanlifiedNum: 0,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantityNum: 0,
        majQuantityNum: 0,
        minQuantityNum: 0,
        checkResult: '3', // 默认为待检
        outDate: null,
        inspectDate: null,
        inspectorId: null,
        inspectorName: '', // 新增，显示检测人员姓名
        status: '1', // 默认为草稿
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null
      },
      // 表单校验
      rules: {
        oqcCode: [
          { required: true, message: "出货检验单编号不能为空", trigger: "blur" }
        ],
        oqcName: [
          { required: true, message: "出货检验单名称不能为空", trigger: "blur" }
        ],
        templateId: [
          { required: true, message: "检验模板ID不能为空", trigger: "blur", validator: (rule, value, callback) => {
            if (this.form.oqcId && !value) {
              callback(new Error("检验模板ID不能为空"));
            } else {
              callback();
            }
          }}
        ],
        templateName: [
          { required: true, message: "检验模板名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "单据状态不能为空", trigger: "change" }
        ],
        sourceDocType: [
          { required: true, message: "来源单据类型不能为空", trigger: "change" }
        ],
        sourceDocCode: [
          { required: true, message: "来源单据编号不能为空", trigger: "blur" }
        ],
        sourceDocId: [
          { required: true, message: "来源单据ID不能为空", trigger: "blur" }
        ],
        customerId: [
          { required: true, message: "客户ID不能为空", trigger: "blur" }
        ],
        customerCode: [
          { required: true, message: "客户编码不能为空", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "产品ID不能为空", trigger: "blur" }
        ],
        productCode: [
          { required: true, message: "产品编码不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        productSfn: [
          { required: true, message: "产品规格型号不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        quantityOutNum: [
          { required: true, message: "发货数量不能为空", trigger: "blur" }
        ],
        quantityCheckNum: [
          { required: true, message: "本次检测数量不能为空", trigger: "blur" }
        ],
        quantityUnqualifiedNum: [
          { required: true, message: "不合格数不能为空", trigger: "blur" }
        ],
        quantityQuanlifiedNum: [
          { required: true, message: "合格数量不能为空", trigger: "blur" }
        ],
        checkResult: [
          { required: true, message: "检测结果不能为空", trigger: "change" }
        ],
        outDate: [
          { required: true, message: "出货日期不能为空", trigger: "change" }
        ],
        inspectDate: [
          { required: true, message: "检测日期不能为空", trigger: "change" }
        ],
        inspectorId: [
          { required: true, message: "检测人员不能为空", trigger: "change" },
          { type: "string", message: "检测人员必须是字符串", trigger: "change" }
        ],
        crRate: [
          { required: true, message: "致命缺陷率不能为空", trigger: "blur" }
        ],
        majRate: [
          { required: true, message: "严重缺陷率不能为空", trigger: "blur" }
        ],
        minRate: [
          { required: true, message: "轻微缺陷率不能为空", trigger: "blur" }
        ],
        crQuantityNum: [
          { required: true, message: "致命缺陷数量不能为空", trigger: "blur" }
        ],
        majQuantityNum: [
          { required: true, message: "严重缺陷数量不能为空", trigger: "blur" }
        ],
        minQuantityNum: [
          { required: true, message: "轻微缺陷数量不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    visible(val) {
      this.open = val;
      if (val) {
        // 打开表单时，如果没有oqcId，则重置表单
        if (!this.oqcId) {
          this.reset();
        }
      }
    },
    open(val) {
      this.$emit("update:visible", val);
    },
    oqcId: {
      handler(val) {
        if (val) {
          this.getOqcDetail();
        } else {
          this.reset();
        }
      },
      immediate: true
    },
    'form.oqcId': {
      handler(val) {
        // 当 form.oqcId 变为 null 且当前标签是检测项时，自动切换到基本信息标签
        if (!val && this.activeTab === 'testItems') {
          this.activeTab = 'basicInfo';
        }
      },
      immediate: true
    },
    // 监听检测数量变化
    'form.quantityCheckNum': function(val) {
      if (val !== undefined) {
        // 检查是否满足最小检测数量要求
        // 新增条件：仅当不是0值时才检查（避免取消操作时的警告）
        if (this.templateParams.quantityCheckNum > 0 && val > 0 && val < this.templateParams.quantityCheckNum) {
          this.$message.warning(`检测数量(${val})不能低于最小检测数量(${this.templateParams.quantityCheckNum})`);
        }
        
        // 自动计算合格数量
        this.updateQualifiedQuantity();
      }
    },
    // 监听不合格数变化
    'form.quantityUnqualifiedNum': function(val) {
      if (val !== undefined) {
        // 自动计算合格数量
        this.updateQualifiedQuantity();
        
        // 检查是否超出最大不合格数，自动设置检测结果
        this.autoCheckResult();
      }
    }
  },
  mounted() {
    // 确保组件挂载时表单被正确初始化
    if (!this.oqcId) {
      this.reset();
    }
  },
  methods: {
    // 更新合格数量
    updateQualifiedQuantity() {
      const checkNum = Number(this.form.quantityCheckNum) || 0;
      const unqualifiedNum = Number(this.form.quantityUnqualifiedNum) || 0;
      
      // 确保不合格数不大于检测数量
      if (unqualifiedNum > checkNum) {
        this.$notify({
          title: '数量调整',
          message: `不合格数(${unqualifiedNum})不能大于检测数量(${checkNum})，已自动调整`,
          type: 'warning',
          duration: 3000
        });
        this.form.quantityUnqualifiedNum = checkNum;
        this.form.quantityQuanlifiedNum = 0;
      } else {
        // 自动计算合格数
        this.form.quantityQuanlifiedNum = checkNum - unqualifiedNum;
      }
      
      // 验证合格数和不合格数之和是否等于检测数量
      const totalCount = Number(this.form.quantityQuanlifiedNum || 0) + Number(this.form.quantityUnqualifiedNum || 0);
      if (totalCount !== checkNum) {
        console.error(`数量验证失败: 合格数(${this.form.quantityQuanlifiedNum}) + 不合格数(${this.form.quantityUnqualifiedNum}) = ${totalCount}，不等于检测数量(${checkNum})`);
        // 强制纠正
        this.form.quantityQuanlifiedNum = checkNum - Number(this.form.quantityUnqualifiedNum || 0);
      }
      
      // 检查是否超出最大不合格数限制
      this.autoCheckResult();
    },
    
    // 自动判断检测结果
    autoCheckResult() {
      const checkNum = Number(this.form.quantityCheckNum) || 0;
      if (checkNum <= 0) return;
      
      const unqualifiedNum = Number(this.form.quantityUnqualifiedNum) || 0;
      
      // 如果有最大不合格数限制且超出限制，自动设为不合格
      if (this.templateParams.quantityUnqualifiedNum > 0 && 
          unqualifiedNum > this.templateParams.quantityUnqualifiedNum) {
        
        if (this.form.checkResult !== '2') {
          console.log(`不合格数(${unqualifiedNum})超过最大不合格数(${this.templateParams.quantityUnqualifiedNum})，自动设置为不合格`);
          this.form.checkResult = '2'; // 设置为不合格
          this.$message.warning(`不合格数超过限制，已自动设置为不合格`);
        }
      } else if (unqualifiedNum === 0 && checkNum > 0 && this.form.checkResult === '3') {
        // 如果没有不合格品且检测数大于0，自动设置为合格
        this.form.checkResult = '1';
      }
    },
    
    // 打开出货单选择对话框
    openSalesSelector() {
      this.salesDialogVisible = true;
      this.getSalesList();
    },

    // 获取出货单列表
    getSalesList() {
      this.salesLoading = true;
      console.log('出货单查询参数:', this.salesQueryParams);
      // 调用API获取出货单列表
      selectCkProductSales(this.salesQueryParams)
        .then(response => {
          console.log('完整API响应:', response);
          // 适配不同的返回格式，尝试获取实际的数据列表
          if (Array.isArray(response)) {
            this.salesList = response;
          } else if (response && typeof response === 'object') {
            // 处理TableDataInfo格式的返回，它通常包含rows属性
            if (response.rows) {
              this.salesList = response.rows;
            } else if (response.data && response.data.rows) {
              this.salesList = response.data.rows;
            } else if (response.data && Array.isArray(response.data)) {
              this.salesList = response.data;
            } else if (response.data && response.data.list) {
              this.salesList = response.data.list;
            } else if (response.list) {
              this.salesList = response.list;
            } else {
              this.salesList = [];
              console.warn('无法从响应中提取数据列表:', response);
            }
          } else {
            this.salesList = [];
            console.warn('无效的响应格式:', response);
          }
          
          console.log('处理后的salesList:', this.salesList);
          this.salesLoading = false;
        })
        .catch(error => {
          console.error('获取出货单列表失败:', error);
          this.salesLoading = false;
          this.$message.error('获取出货单列表失败');
        });
    },

    // 处理出货单查询
    handleSalesQuery() {
      this.getSalesList();
    },

    // 处理出货单选择
    handleSalesSelect(row) {
      if (row) {
        this.form.sourceDocCode = row.sales_code;
        this.form.sourceDocId = row.sales_id;
        this.form.batchCode = row.batch_code;
        this.form.outDate = this.formatDate(row.sales_date);
        this.form.customerId = row.customer_id;
        this.form.customerCode = row.customer_code;
        this.form.customerName = row.customer_name;
        
        // 添加产品信息回显
        this.form.productId = row.product_id;
        this.form.productCode = row.product_code;
        this.form.productName = row.product_name;
        this.form.productSfn = row.specification;
        this.form.unit = row.unit;

        // 清除sourceDocCode字段的验证提示
        if (this.$refs.form) {
          this.$refs.form.clearValidate(['sourceDocCode']);
          
          // 清除产品相关字段的验证提示
          this.$refs.form.clearValidate(['productId', 'productCode', 'productName', 'productSfn', 'unit']);
        }

        this.salesDialogVisible = false;
        this.$message.success('出货单选择成功');
        
        // 根据产品ID查询检测方案
        this.findTemplateByProductId(row.product_id);
      }
    },
    
    // 根据产品ID查询对应的质检方案ID
    findTemplateByProductId(productId) {
      if (!productId) {
        console.warn('【查询检测方案】产品ID为空，无法查询');
        return;
      }
      
      console.log('【查询检测方案】开始通过产品ID查询，产品ID：', productId);
      
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在查询对应的检测方案...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      selectQcTemplateProductProductCode(productId).then(response => {
        loadingInstance.close();
        console.log('【通过产品ID查询】原始返回数据:', response);
        
        // 判断响应是否有效
        if (response) {
          this.setTemplateInfo(response);
          
          // 如果是编辑模式，检查检测结果是否符合规范
          if (this.form.oqcId) {
            // 等待下一个事件循环再检查，确保表单数据已更新
            this.$nextTick(() => {
              // 重新验证检测数量和不合格数
              this.autoCheckResult();
              
              // 确保合格数量计算正确
              const checkNum = Number(this.form.quantityCheckNum) || 0;
              const unqualifiedNum = Number(this.form.quantityUnqualifiedNum) || 0;
              this.form.quantityQuanlifiedNum = checkNum - unqualifiedNum;
            });
          }
        } else {
          this.$message.warning('未找到对应的检测方案，请手动选择');
        }
      }).catch(error => {
        loadingInstance.close();
        console.error('【错误】通过产品ID查询检测方案异常', error);
        this.$message.error('查询检测方案失败: ' + (error.message || '未知错误'));
      });
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toISOString().split('T')[0];
    },
    
    // 根据物料编码查询对应的质检方案ID
    findTemplateByMaterialCode(materialCode) {
      if (!materialCode) {
        console.warn('【查询检测方案】物料编码为空，无法查询');
        return;
      }
      
      console.log('【查询检测方案】开始查询，物料编码：', materialCode);
      
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在查询对应的检测方案...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      selectQcTemplateProductMaterialCode(materialCode).then(response => {
        loadingInstance.close();
        console.log('【通过物料编码查询】原始返回数据:', response);
        
        if (response) {
          this.setTemplateInfo(response);
        } else {
          console.warn('【通过物料编码查询】未找到检测方案，请手动选择');
          this.$message.info('未找到对应的检测方案，请手动选择');
        }
      }).catch(error => {
        loadingInstance.close();
        console.error('【错误】通过物料编码查询检测方案异常', error);
      });
    },
    
    // 设置模板信息到表单
    setTemplateInfo(templateData) {
      if (!templateData) return;
      
      console.log('【设置模板信息】质检方案数据:', templateData);
      
      // 提取模板ID和名称
      let templateId, templateCode, templateName;
      
      // 检查返回值类型
      if (typeof templateData === 'object') {
        // 提取模板基础信息
        templateId = templateData.template_id || templateData.templateId || templateData;
        templateCode = templateData.template_code || templateData.templateCode || '';
        templateName = templateData.template_name || templateData.templateName || '';
        
        // 设置质检规范参数
        if (templateData.quantity_check_num !== undefined) {
          this.form.quantityMinCheckNum = templateData.quantity_check_num;
        }
        if (templateData.quantity_unqualified_num !== undefined) {
          this.form.quantityMaxUnqualifiedNum = templateData.quantity_unqualified_num;
        }
        if (templateData.cr_rate !== undefined) {
          this.form.crRate = templateData.cr_rate;
        }
        if (templateData.maj_rate !== undefined) {
          this.form.majRate = templateData.maj_rate;
        }
        if (templateData.min_rate !== undefined) {
          this.form.minRate = templateData.min_rate;
        }
        
        // 将规范参数保存到模板参数对象
        this.templateParams = {
          quantityCheckNum: this.form.quantityMinCheckNum,
          quantityUnqualifiedNum: this.form.quantityMaxUnqualifiedNum,
          crRate: this.form.crRate,
          majRate: this.form.majRate,
          minRate: this.form.minRate
        };
        
      } else {
        templateId = templateData;
      }
      
      // 确保模板ID为数字
      const numTemplateId = Number(templateId);
      if (isNaN(numTemplateId)) {
        console.warn('获取到的检测方案ID格式不正确');
        return;
      }
      
      // 设置模板ID和名称
      this.form.templateId = numTemplateId;
      if (templateCode) this.form.templateCode = templateCode;
      if (templateName) this.form.templateName = templateName;
      
      // 提示用户已自动应用检测方案的规定
      this.$notify({
        title: '检测方案已应用',
        message: `已应用检测方案规定：最低检测数=${this.form.quantityMinCheckNum}，最大不合格数=${this.form.quantityMaxUnqualifiedNum}`,
        type: 'success',
        duration: 5000
      });
      
      console.log('设置的质检规范:', {
        最低检测数: this.form.quantityMinCheckNum,
        最大不合格数: this.form.quantityMaxUnqualifiedNum,
        致命缺陷率: this.form.crRate,
        严重缺陷率: this.form.majRate,
        轻微缺陷率: this.form.minRate
      });
    },
    
    // 修改打开检验模板选择器方法
    openTemplatePlanSelector() {
      // 检查是否已有检测方案ID
      if (this.form.templateId) {
        this.$confirm('当前已选择检测方案，是否重新选择?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户确认重新选择
          this.templateSelectorVisible = true;
        }).catch(() => {
          // 用户取消重新选择
          this.$message.info('已取消重新选择');
        });
      } else {
        // 直接打开选择对话框
        this.templateSelectorVisible = true;
      }
    },

    // 处理检验模板选择
    handleTemplateSelect(plan) {
      console.log('选择的检验模板:', plan);
      if (plan) {
        this.form.templateId = plan.templateId;
        this.form.templateCode = plan.templateCode;
        this.form.templateName = plan.templateName;

        // 清除templateId字段的验证提示
        if (this.$refs.form) {
          this.$refs.form.clearValidate(['templateId']);
        }

        this.$message.success('检验模板选择成功');
      }
    },

    // 打开员工选择弹窗
    openUserDialog() {
      this.userDialogVisible = true;
    },

    // 处理员工选择
    handleUserConfirm(selection) {
      if (selection && selection.length > 0) {
        const selectedUser = selection[0];
        
        // 修改：将用户名称存入inspectorId字段，不再存用户ID
        this.form.inspectorId = selectedUser.nickName || selectedUser.userName;
        
        // 保持inspectorName字段不变，仍然存储用户名称
        this.form.inspectorName = selectedUser.nickName || selectedUser.userName;
        
        console.log('选择检测人员:', selectedUser);
        console.log('修改后的检测人员信息:', {
          inspectorId字段存储: this.form.inspectorId,
          inspectorName字段存储: this.form.inspectorName
        });
      }
      this.userDialogVisible = false;
    },

    // 监听输入变化，清除对应字段的验证提示
    handleInputChange(field) {
      if (this.$refs.form && this.form[field]) {
        this.$refs.form.clearValidate([field]);
      }
    },

    // 自动生成编码
    handleGenerateCode() {
      this.codeLoading = true;
      // 调用 API 获取自动编号，此处使用编码类型 4（出货检验单编码）
      getAutoNumbers(4).then(response => {
        if (response.code === 200) {
          this.form.oqcCode = response.msg;
          if (this.$refs.form) {
            this.$refs.form.clearValidate(['oqcCode']);
          }
          this.$message.success('编码生成成功');
        } else {
          this.$message.error('编码生成失败');
        }
      }).catch(() => {
        this.$message.error('编码生成异常');
      }).finally(() => {
        this.codeLoading = false;
      });
    },

    // 获取出货检验单详细信息
    async getOqcDetail() {
      if (!this.oqcId) return;
      const id = Number(this.oqcId);
      try {
        const response = await getOqc(id);
        if (response.data) {
          this.form = response.data;
          
          // 处理检测人员字段显示问题
          console.log('编辑模式 - 处理前的检测人员数据:', {
            inspectorId: this.form.inspectorId,
            inspectorName: this.form.inspectorName
          });
          
          // 如果inspectorId存在但inspectorName不存在，则将inspectorId的值复制给inspectorName
          if (this.form.inspectorId && !this.form.inspectorName) {
            this.form.inspectorName = String(this.form.inspectorId);
            console.log('已将inspectorId的值复制给inspectorName:', this.form.inspectorName);
          }
          
          // 如果我们现在使用名称作为inspectorId字段的值，确保类型正确
          if (this.form.inspectorId) {
            this.form.inspectorId = String(this.form.inspectorId);
          }
          
          // 编辑模式下将单据状态设为"已审核"
          this.form.status = '3';
          console.log('编辑模式 - 单据状态已设置为已审核(3)');
          
          console.log('编辑模式 - 处理后的检测人员数据:', {
            inspectorId: this.form.inspectorId,
            inspectorName: this.form.inspectorName
          });
          
          // 编辑模式下，如果有产品ID，也查询对应的检测方案
          if (this.form.productId) {
            console.log('编辑模式 - 根据产品ID查询检测方案:', this.form.productId);
            this.findTemplateByProductId(this.form.productId);
          }
        } else {
          this.$message.error("获取出货检验单详情失败");
        }
      } catch (error) {
        console.error("获取出货检验单详情失败:", error);
        this.$message.error("获取出货检验单详情失败");
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      // 不再调用reset()，避免将检测数量重置为0触发校验警告
      this.$emit("cancel");
    },
    // 表单重置
    reset() {
      this.form = {
        oqcId: null,
        oqcCode: null,
        oqcName: null,
        templateId: null,
        templateCode: null,
        templateName: null,
        sourceDocId: null,
        sourceDocType: '1', // 默认为出货单
        sourceDocCode: null,
        sourceLineId: null,
        customerId: null,
        customerCode: null,
        customerName: null,
        batchCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSfn: null,
        unit: null,
        quantityMinCheckNum: 0,
        quantityMaxUnqualifiedNum: 0,
        quantityOutNum: 0,
        quantityCheckNum: 0,
        quantityUnqualifiedNum: 0,
        quantityQuanlifiedNum: 0,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantityNum: 0,
        majQuantityNum: 0,
        minQuantityNum: 0,
        checkResult: '3', // 默认为待检
        outDate: null,
        inspectDate: null,
        inspectorId: null,
        inspectorName: '', // 新增，显示检测人员姓名
        status: '2', // 新增模式默认为已提交
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null
      };
      // 重置为基本信息标签页
      this.activeTab = 'basicInfo';

      // 确保表单验证状态重置
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
        this.$refs["form"].clearValidate();
      }

      // 如果OqcLineTable组件存在，也重置它
      if (this.$refs["oqcLineTable"]) {
        this.$refs["oqcLineTable"].reset && this.$refs["oqcLineTable"].reset();
      }
    },
    // 提交按钮
    submitForm() {
      // 如果是新增模式，移除模板ID的验证
      if (!this.form.oqcId && this.$refs["form"]) {
        this.$refs["form"].clearValidate(['templateId']);
      }
      
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保inspectorId是字符串类型
          if (this.form.inspectorId) {
            this.form.inspectorId = String(this.form.inspectorId);
          }
          
          // 检查检测数量是否满足最低要求（仅当设置了检测方案时且不是编辑模式）
          const checkNum = Number(this.form.quantityCheckNum) || 0;
          const minCheckNum = Number(this.form.quantityMinCheckNum) || 0;
          
          console.log(`提交表单 - 当前检测数量: ${checkNum}, 最低检测数量: ${minCheckNum}, 编辑模式: ${Boolean(this.form.oqcId)}`);
          
          // 只在新增模式下检查
          if (!this.form.oqcId && minCheckNum > 0 && checkNum < minCheckNum) {
            this.$confirm(`检测数量(${checkNum})低于规定最低检测数(${minCheckNum})，是否确认提交？`, '检测数量不足', {
              confirmButtonText: '确认提交',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.executeSubmit();
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消提交'
              });
            });
          } else {
            // 检测数量符合要求、无最低要求或编辑模式，直接提交
            this.executeSubmit();
          }
        }
      });
    },
    
    // 执行实际提交操作
    async executeSubmit() {
      // 使用Element UI的loading服务
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在提交数据，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      try {
        // 如果是新增且开启系统编号，获取真正的消费编号
        if (!this.form.oqcId && this.isSystemCode) {
          try {
            const response = await getAutoNumbersConsume(4);
            if (response && response.code === 200) {
              this.form.oqcCode = response.msg;
            } else {
              this.$message.error('获取最终编号失败，请重试');
              loadingInstance.close();
              return;
            }
          } catch (error) {
            this.$message.error('获取最终编号失败，请重试');
            loadingInstance.close();
            return;
          }
        }

        if (this.form.oqcId != null) {
          // 修改操作
          updateOqc(this.form).then(response => {
            loadingInstance.close();
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.$emit("success", {...this.form, isNew: false});
            this.$emit("update:visible", false);
          }).catch(error => {
            loadingInstance.close();
            this.$modal.msgError("修改失败: " + (error.message || '未知错误'));
            console.error("修改出货检验单失败:", error);
          });
        } else {
          // 新增操作 - 先转换数据格式
          const formData = { ...this.form };
          
          // 确保必填字段存在
          if (!formData.oqcCode) {
            this.$message.error("出货检验单编号不能为空");
            loadingInstance.close();
            return;
          }
          
          if (!formData.oqcName) {
            this.$message.error("出货检验单名称不能为空");
            loadingInstance.close();
            return;
          }
          
          // 一些特定字段需要保持字符串类型
          const stringFields = ['oqcCode', 'oqcName', 'customerCode', 'customerName',
                               'batchCode', 'productCode', 'productName', 'productSfn', 'unit',
                               'inspectorId', 'inspectorName',
                               'remark', 'attr1', 'attr2', 'attr3', 'attr4'];
                               
          // 在新增模式下，如果存在模板相关信息，才将其添加到stringFields
          if (formData.templateCode) {
            stringFields.push('templateCode', 'templateName');
          }
          
          // 只转换确定需要数值类型的字段，并确保转换结果是有效数字
          const numberFields = ['sourceDocId', 'sourceDocType', 'customerId', 'productId',
                               'quantityMinCheckNum', 'quantityMaxUnqualifiedNum', 'quantityOutNum', 
                               'quantityCheckNum', 'quantityUnqualifiedNum', 'quantityQuanlifiedNum',
                               'crQuantityNum', 'majQuantityNum', 'minQuantityNum', 'checkResult', 'status'];
                               
          // 在新增模式下，如果存在模板ID，将其添加到numberFields
          if (formData.templateId) {
            numberFields.push('templateId');
          }
          
          // 确保字符串字段是字符串类型
          stringFields.forEach(key => {
            if (formData[key] !== null && formData[key] !== undefined) {
              formData[key] = String(formData[key]);
            }
          });
          
          // 谨慎转换数值字段
          numberFields.forEach(key => {
            if (formData[key] !== null && formData[key] !== undefined) {
              // 如果是空字符串，设为0或null
              if (formData[key] === '') {
                formData[key] = 0;
              } else {
                const num = Number(formData[key]);
                // 检查转换后的值是否为有效数字
                if (!isNaN(num)) {
                  formData[key] = num;
                } else {
                  // 如果转换结果无效，保持原值
                  console.warn(`字段 ${key} 的值 "${formData[key]}" 无法转换为有效数字，保持原值`);
                }
              }
            }
          });
          
          // 移除undefined和null字段，防止后端解析错误
          Object.keys(formData).forEach(key => {
            if (formData[key] === undefined || formData[key] === null) {
              delete formData[key];
            }
          });
          
          console.log('准备提交的表单数据:', JSON.stringify(formData));
          
          // 使用原始表单数据直接提交，避免转换问题
          console.log('最终提交的表单数据:', JSON.stringify(formData));
          
          addOqc(formData)
            .then(response => {
            loadingInstance.close();
            this.$modal.msgSuccess("新增成功");
            // 如果是新增成功，获取返回的数据
            const data = response.data || {};

            // 合并表单数据和返回的数据，并添加isNew标志
            const formData = {...this.form, ...data, isNew: true};

            // 确保有oqcCode用于后续查询
            if (!formData.oqcCode && this.form.oqcCode) {
              formData.oqcCode = this.form.oqcCode;
            }

            this.open = false;
            this.$emit("success", formData);
            this.$emit("update:visible", false);
          }).catch(error => {
            loadingInstance.close();
            
            // 增强错误日志，帮助排查问题
            console.error("新增出货检验单失败:", error);
            console.error("错误详情:", {
              message: error.message,
              status: error.response?.status,
              statusText: error.response?.statusText,
              data: error.response?.data
            });
            
            if (error.response && error.response.status === 404) {
              this.$modal.msgError("服务器接口不存在，请检查接口地址是否正确");
            } else if (error.response && error.response.status === 500) {
              this.$modal.msgError("服务器内部错误: " + (error.response.data?.msg || '未知错误'));
            } else if (error.message && error.message.includes('Network Error')) {
              this.$modal.msgError("网络错误，无法连接到服务器");
            } else {
              this.$modal.msgError("新增失败: " + (error.message || '未知错误'));
            }
          });
        }
      } catch (error) {
        console.error('执行提交操作时出错:', error);
        loadingInstance.close();
        this.$message.error('提交数据失败: ' + (error.message || '未知错误'));
      }
    },
    // 处理发货数量变化
    handleOutNumChange(value) {
      const outNum = Number(value) || 0;
      this.form.quantityOutNum = outNum;
      
      // 确保检测数量不超过发货数量
      const checkNum = Number(this.form.quantityCheckNum) || 0;
      if (checkNum > outNum) {
        this.$notify({
          title: '数量调整',
          message: `由于发货数量变更为${outNum}，检测数量(${checkNum})已自动调整`,
          type: 'warning',
          duration: 3000
        });
        this.form.quantityCheckNum = outNum;
        this.handleQuantityChange(); // 触发检测数量变化处理
      }
    },
    // 处理检测数量变更
    handleQuantityChange() {
      // 确保检测数量为数字
      const checkNum = Number(this.form.quantityCheckNum) || 0;
      const outNum = Number(this.form.quantityOutNum) || 0;
      
      console.log(`检测数量变更 - 当前检测数量: ${checkNum}, 最低检测数量: ${this.form.quantityMinCheckNum}`);
      
      // 检查发货数量约束
      if (outNum > 0 && checkNum > outNum) {
        this.$notify({
          title: '数量调整',
          message: `检测数量(${checkNum})不能超过发货数量(${outNum})，已自动调整`,
          type: 'warning',
          duration: 3000
        });
        this.form.quantityCheckNum = outNum;
      }
      
      // 保持不合格数不变，更新合格数
      const unqualifiedNum = Number(this.form.quantityUnqualifiedNum) || 0;
      if (unqualifiedNum > checkNum) {
        // 如果不合格数大于检测数量，调整不合格数
        this.$notify({
          title: '数量调整',
          message: `由于检测数量变更为${checkNum}，不合格数(${unqualifiedNum})已调整`,
          type: 'warning',
          duration: 3000
        });
        this.form.quantityUnqualifiedNum = checkNum;
        this.form.quantityQuanlifiedNum = 0;
      } else {
        // 根据检测数量和不合格数计算合格数
        this.form.quantityQuanlifiedNum = checkNum - unqualifiedNum;
      }
      
      // 验证合格数与不合格数之和是否等于检测数量
      const totalCount = Number(this.form.quantityQuanlifiedNum || 0) + Number(this.form.quantityUnqualifiedNum || 0);
      if (totalCount !== checkNum) {
        console.log(`数量验证: 合格数(${this.form.quantityQuanlifiedNum}) + 不合格数(${this.form.quantityUnqualifiedNum}) = ${totalCount}，检测数量(${checkNum})`);
        // 强制纠正
        this.form.quantityQuanlifiedNum = checkNum - Number(this.form.quantityUnqualifiedNum || 0);
      }
      
      // 重新计算缺陷率
      this.calculateDefectRates();
      
      // 检查是否满足最低检测数量（仅当有设置最低检测数量时检查，且不是编辑模式，并且检测数量不为0）
      const minCheckNum = Number(this.form.quantityMinCheckNum) || 0;
      if (minCheckNum > 0 && checkNum > 0 && checkNum < minCheckNum && !this.form.oqcId) {
        this.$notify({
          title: '检测数量不足',
          message: `检测数量(${checkNum})低于规定最低检测数(${minCheckNum})`,
          type: 'warning',
          duration: 5000
        });
      }
      
      // 自动检查结果
      this.autoCheckResult();
    },
    // 处理不合格数变化
    handleUnqualifiedNumChange(value) {
      const checkNum = Number(this.form.quantityCheckNum) || 0;
      // 直接使用传入的值，确保拿到最新的输入值
      let unqualifiedNum = Number(value) || 0;
      
      // 确保不合格数为非负整数
      if (unqualifiedNum < 0) {
        unqualifiedNum = 0;
        this.form.quantityUnqualifiedNum = 0;
      }
      
      // 确保不合格数不大于检测数量
      if (unqualifiedNum > checkNum) {
        this.$notify({
          title: '数量调整',
          message: `不合格数(${unqualifiedNum})不能大于检测数量(${checkNum})，已自动调整`,
          type: 'warning',
          duration: 3000
        });
        unqualifiedNum = checkNum;
        this.form.quantityUnqualifiedNum = checkNum;
      }
      
      // 计算合格数
      this.form.quantityQuanlifiedNum = checkNum - unqualifiedNum;
      
      // 确保组件中显示的值是正确的，防止由于精度问题导致界面值不正确
      this.$nextTick(() => {
        this.form.quantityUnqualifiedNum = unqualifiedNum;
        this.form.quantityQuanlifiedNum = checkNum - unqualifiedNum;
      });
      
      // 检查是否超出最大不合格数并更新检测结果
      this.autoCheckResult();
      
      // 重置缺陷数量
      this.form.crQuantityNum = 0;
      this.form.majQuantityNum = 0;
      this.form.minQuantityNum = 0;

      // 重新计算缺陷率
      this.calculateDefectRates();
    },
    // 处理合格数量变化
    handleQualifiedNumChange(value) {
      const checkNum = Number(this.form.quantityCheckNum) || 0;
      let qualifiedNum = Number(value) || 0;
      
      // 确保合格数为非负整数
      if (qualifiedNum < 0) {
        qualifiedNum = 0;
        this.form.quantityQuanlifiedNum = 0;
      }
      
      // 确保合格数不大于检测数量
      if (qualifiedNum > checkNum) {
        this.$notify({
          title: '数量调整',
          message: `合格数量(${qualifiedNum})不能大于检测数量(${checkNum})，已自动调整`,
          type: 'warning',
          duration: 3000
        });
        qualifiedNum = checkNum;
        this.form.quantityQuanlifiedNum = checkNum;
      }
      
      // 根据合格数计算不合格数
      const newUnqualifiedNum = checkNum - qualifiedNum;
      this.form.quantityUnqualifiedNum = newUnqualifiedNum;
      
      // 确保组件中显示的值是正确的，防止由于精度问题导致界面值不正确
      this.$nextTick(() => {
        this.form.quantityQuanlifiedNum = qualifiedNum;
        this.form.quantityUnqualifiedNum = checkNum - qualifiedNum;
      });
      
      // 检查是否超出最大不合格数并更新检测结果
      this.autoCheckResult();
      
      // 重新计算缺陷率
      this.calculateDefectRates();
    },
    
    // 计算缺陷率
    calculateDefectRates() {
      const checkNum = Number(this.form.quantityCheckNum) || 0;
      if (checkNum <= 0) {
        // 如果检测数量为0或不存在，清空缺陷率
        this.form.crRate = 0;
        this.form.majRate = 0;
        this.form.minRate = 0;
        return;
      }
      
      // 计算各类缺陷率
      const crNum = Number(this.form.crQuantityNum) || 0;
      const majNum = Number(this.form.majQuantityNum) || 0;
      const minNum = Number(this.form.minQuantityNum) || 0;
      
      // 计算百分比，保留两位小数
      this.form.crRate = Number(((crNum / checkNum) * 100).toFixed(2));
      this.form.majRate = Number(((majNum / checkNum) * 100).toFixed(2));
      this.form.minRate = Number(((minNum / checkNum) * 100).toFixed(2));
      
      console.log('缺陷率计算结果:', {
        致命缺陷率: this.form.crRate,
        严重缺陷率: this.form.majRate,
        轻微缺陷率: this.form.minRate
      });
      
      // 当缺陷率计算完成后，自动计算不合格数
      // 所有缺陷数量应等于不合格数
      const calculatedUnqualified = crNum + majNum + minNum;
      if (this.form.quantityUnqualifiedNum !== calculatedUnqualified) {
        console.log(`缺陷数量总和(${calculatedUnqualified})与不合格数(${this.form.quantityUnqualifiedNum})不一致，已自动调整不合格数`);
        
        // 保存旧的不合格数用于日志
        const oldUnqualifiedNum = this.form.quantityUnqualifiedNum;
        
        // 更新不合格数和合格数
        this.form.quantityUnqualifiedNum = calculatedUnqualified;
        this.form.quantityQuanlifiedNum = checkNum - calculatedUnqualified;
        
        // 记录详细的调整信息
        console.log(`不合格数已从${oldUnqualifiedNum}调整为${calculatedUnqualified}`);
        
        // 使用nextTick确保数据已更新
        this.$nextTick(() => {
          // 立即检查调整后的不合格数是否超过最大允许值，并更新检测结果
          this.autoCheckResult();
          
          // 如果调整后的不合格数超过了最大允许值，强制发出额外提示
          const maxUnqualified = Number(this.form.quantityMaxUnqualifiedNum) || 0;
          if (maxUnqualified > 0 && calculatedUnqualified > maxUnqualified) {
            this.$notify({
              title: '缺陷数量导致不合格',
              message: `根据缺陷数量统计，不合格数已调整为${calculatedUnqualified}，超过最大允许值${maxUnqualified}，检测结果已设为不合格`,
              type: 'error',
              duration: 8000,
              showClose: true
            });
          }
        });
      } else {
        // 自动检查是否需要更新检测结果
        this.autoCheckResult();
      }
    },
    
    // 自动检查结果
    autoCheckResult() {
      const checkNum = Number(this.form.quantityCheckNum) || 0;
      if (checkNum <= 0) return;
      
      const unqualifiedNum = Number(this.form.quantityUnqualifiedNum) || 0;
      const maxUnqualifiedNum = Number(this.form.quantityMaxUnqualifiedNum) || 0;
      const oldCheckResult = this.form.checkResult;
      
      console.log(`执行自动检查: 不合格数=${unqualifiedNum}, 最大允许不合格数=${maxUnqualifiedNum}, 当前检测结果=${oldCheckResult}`);
      
      // 如果有最大不合格数限制且超出限制，自动设为不合格
      if (maxUnqualifiedNum > 0 && unqualifiedNum > maxUnqualifiedNum) {
        
        // 强制设置为不合格，不管之前是什么状态
        this.form.checkResult = "2"; // 设置为不合格
        
        // 仅当检测结果发生变化时记录日志和显示提示
        if (oldCheckResult !== "2") {
          console.log(`不合格数(${unqualifiedNum})超过最大不合格数(${maxUnqualifiedNum})，已将检测结果从"${oldCheckResult}"修改为"不合格(2)"`);
          
          // 显示更突出的警告提示
          this.$notify({
            title: '检测结果已更新为不合格',
            message: `不合格数(${unqualifiedNum})已超过最大允许不合格数(${maxUnqualifiedNum})，系统已自动将检测结果设置为"不合格"`,
            type: 'error', // 使用error类型使提示更醒目
            duration: 6000,
            showClose: true,
            position: 'top-right'
          });
        } else {
          console.log(`检测结果已经是不合格(2)，无需修改`);
        }
      } else if (unqualifiedNum === 0 && checkNum > 0) {
        // 如果没有不合格品且检测数大于0，自动设置为合格
        if (this.form.checkResult !== "1") {
          this.form.checkResult = "1";
          console.log('检测数量为' + checkNum + '，不合格数为0，自动设置为合格');
        }
      } else if (unqualifiedNum > 0 && maxUnqualifiedNum > 0 && unqualifiedNum <= maxUnqualifiedNum && this.form.checkResult === "2") {
        // 如果不合格数减少到最大允许值以内，可以恢复为合格状态
        this.form.checkResult = "1";
        this.$notify({
          title: '检测结果已更新为合格',
          message: `不合格数(${unqualifiedNum})在允许范围内(最大允许${maxUnqualifiedNum})，检测结果已自动设置为"合格"`,
          type: 'success',
          duration: 4000
        });
      }
    }
  }
};
</script>
<style scoped>
.oqc-form {
  display: flex;
  flex-direction: column;
  height: 580px;
  width: 100%;
  min-height: 580px;
  max-height: 580px;
}

.form-tabs {
  margin-bottom: 15px;
  background: #fff;
  padding: 10px 20px 0;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-content-area {
  flex: 1;
  overflow-y: auto;
  min-height: 450px;
  max-height: 450px;
  padding-right: 5px;
}

.form-card {
  margin-bottom: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-weight: bold;
  color: #409EFF;
}

.form-container {
  padding: 20px 0;
}

.form-footer {
  height: 50px;
  text-align: center;
  background: #fff;
  padding: 8px 0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 10px;
  flex-shrink: 0;
  border-radius: 4px;
}

/* 确保输入框宽度一致 */
.el-input {
  width: 100%;
}

/* 输入框内容显示优化 */
::v-deep .el-input__inner {
  padding-right: 15px;
  text-overflow: ellipsis;
  font-size: 14px;
}

/* 调整表单项之间的间距 */
.el-form-item {
  margin-bottom: 22px;
}

/* 标签宽度优化 */
::v-deep .el-form-item__label {
  width: 120px !important;
  padding-right: 12px;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: right;
}

/* 整体字体大小略微缩小，增加内容密度 */
.oqc-form {
  font-size: 0.95em;
}

/* 调整行间距以适应更多内容 */
.el-row {
  margin-bottom: 10px;
}

/* 数字输入框样式调整 */
.el-input-number.el-input-number--medium {
  width: 100%;
}

::v-deep .el-input-number__decrease,
::v-deep .el-input-number__increase {
  background-color: #f5f7fa;
}

/* 标签页样式增强 */
::v-deep .el-tabs__item {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  padding: 0 20px;
}

::v-deep .el-tabs__item:hover {
  color: #409EFF;
}

::v-deep .el-tabs__item.is-active {
  color: #409EFF;
  font-weight: bold;
}

/* 自定义滚动条样式 */
.form-content-area::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.form-content-area::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.form-content-area::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

/* 响应式样式调整 */
@media screen and (max-width: 1400px) {
  .oqc-form {
    padding: 5px;
  }

  .el-row {
    margin-left: -10px !important;
    margin-right: -10px !important;
  }

  .el-col {
    padding-left: 10px !important;
    padding-right: 10px !important;
  }
}

/* 按钮内嵌输入框样式 */
.input-with-btn {
  position: relative;
  width: 100%;
}

/* 按钮与输入框组合的样式 */
::v-deep .el-input-group__append {
  padding: 0;
  background-color: transparent;
  border: none;
}

::v-deep .inner-button {
  height: 32px;
  padding: 7px 15px;
  border-radius: 0 4px 4px 0;
  margin-left: 0;
  border-left: 1px solid #dcdfe6;
}

/* 新增分区标题样式 */
.section-header {
  font-size: 14px;
  font-weight: bold;
  margin: 10px 0;
  padding: 5px 0;
  color: #606266;
  border-bottom: 1px solid #ebeef5;
}

/* 检测项容器样式 */
.test-items-container {
  height: 100%;
  overflow: auto;
}

/* 提示信息样式 */
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.form-tip .el-icon {
  margin-right: 5px;
}

.form-tip.warning {
  color: #E6A23C;
}
</style>
